package cn.steel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.domain.entity.Favorite;
import cn.steel.domain.entity.Product;
import cn.steel.domain.entity.User;
import cn.steel.domain.vo.ProductVo;
import cn.steel.mapper.FavoriteMapper;
import cn.steel.mapper.ProductMapper;
import cn.steel.mapper.UserMapper;
import cn.steel.service.FavoriteService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class FavoriteServiceImpl implements FavoriteService {

    private final FavoriteMapper favoriteMapper;
    private final ProductMapper productMapper;
    private final UserMapper userMapper;

    /**
     * 获取收藏夹商品分页列表
     *
     * @param userId 用户 ID
     * @param page   页码
     * @param size   每页大小
     * @return 收藏夹商品分页列表
     */
    @Override
    public Page<ProductVo> getFavoritesPaginated(Long userId, int page, int size) {
        validateBuyer(userId);
        PageHelper.startPage(page, size);
        List<Favorite> favorites = favoriteMapper.findFavoritesByUserId(userId);
        List<ProductVo> productVos = favorites.stream().map(f -> {
            Product product = productMapper.findProductById(f.getProductId());
            if (product == null) {
                return null;
            }
            ProductVo vo = new ProductVo();
            BeanUtil.copyProperties(product, vo);
            vo.setFavoriteId(f.getId()); // 设置收藏记录的 ID
            return vo;
        }).filter(vo -> vo != null).collect(Collectors.toList());

        Page<ProductVo> pageResult = new Page<>();
        BeanUtil.copyProperties(favorites, pageResult);
        pageResult.addAll(productVos);
        return pageResult;
    }

    /**
     * 添加商品到收藏夹
     *
     * @param userId   用户 ID
     * @param productId 商品 ID
     */
    @Override
    @Transactional
    public void addToFavorites(Long userId, Long productId) {
        validateBuyer(userId);
        Product product = productMapper.findProductById(productId);
        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        Favorite existing = favoriteMapper.findByUserAndProduct(userId, productId);
        if (existing != null) {
            return; // 已收藏，忽略
        }
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setProductId(productId);
        favoriteMapper.insertFavorite(favorite);
        log.info("Added favorite: userId={}, productId={}", userId, productId);
    }
    /**
     * 移除收藏夹中的商品
     *
     * @param favoriteId 收藏夹 ID
     */

    @Override
    @Transactional
    public void removeFavorite(Long favoriteId) {
        Favorite favorite = favoriteMapper.findById(favoriteId);
        if (favorite == null) {
            throw new IllegalArgumentException("收藏记录不存在");
        }
        validateBuyer(favorite.getUserId());
        favoriteMapper.deleteFavorite(favoriteId);
        log.info("Removed favorite with id: {}", favoriteId);
    }

    /**
     * 验证用户是否为 BUYER 角色
     *
     * @param userId 用户 ID
     */
    private void validateBuyer(Long userId) {
        User user = userMapper.findUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (!"BUYER".equals(user.getRole())) {
            throw new IllegalArgumentException("仅买家用户可以操作收藏夹");
        }
    }
}